package com.hm.health.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.goodix.libromablecom.sdk.cardiff.CardiffOtaUpdate;
import com.goodix.libtest.activities.FileBrowserActivity;
import com.goodix.libtest.fragments.LogFragment;
import com.hm.health.R;

import java.io.File;

/**
 * OTA升级界面。
 *
 * @author wangchen1
 * @version 2020-09-14
 */
public class OtaUpdateActivity extends AppCompatActivity {
    private static final File logPath = new File(Environment.getExternalStorageDirectory(), "GoodixHBD/log");

    private LogFragment logFragment;

    /**
     * 升级状态文本框。
     */
    private TextView statusText;

    /**
     * 升级按钮。
     */
    private Button startButton;

    /**
     * 浏览按钮。
     */
    private Button browseButton;

    /**
     * 进度条。
     */
    private ProgressBar updateProgressBar;

    /**
     * 选择文件的提示信息文本框。
     */
    private TextView currentFileLabelText;

    /**
     * 选择文件的文件名文本框。
     */
    private TextView currentFileNameText;

    /**
     * 选定的要升级的固件文件。
     */
    private File binFileSelection;

    private CardiffOtaUpdate cardiffOtaUpdate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ota_update);
        setTitle("OTA升级");

        statusText = findViewById(R.id.activity_ota_text_status);
        startButton = findViewById(R.id.activity_ota_button_start);
        browseButton = findViewById(R.id.activity_ota_button_browse);
        updateProgressBar = findViewById(R.id.activity_ota_progressBar);
        currentFileLabelText = findViewById(R.id.activity_ota_text_currentFileLabel);
        currentFileNameText = findViewById(R.id.activity_ota_text_currentFileName);

        logFragment = new LogFragment();

        cardiffOtaUpdate = new CardiffOtaUpdate(this, new CardiffOtaUpdate.Listener() {
            @Override
            public void errorBeforeUpdating(String msg) {
                Toast.makeText(OtaUpdateActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void debugLog(String msg) {
                logFragment.log(msg, false);
            }

            @Override
            public void log(String msg) {
                runOnUiThread(() -> logFragment.log(msg));
            }

            @Override
            public void setProgress(int progress) {
                runOnUiThread(() -> updateProgressBar.setProgress(progress));
            }

            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    statusText.setText("升级成功");
                    statusText.setTextColor(0xFF6DB529);
                    startButton.setEnabled(true);
                    startButton.setText("关闭界面");
                    startButton.setOnClickListener(view -> finish());
                    browseButton.setEnabled(true);
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(() -> {
                    statusText.setText("升级失败");
                    statusText.setTextColor(0xFFFF0000);
                    startButton.setEnabled(true);
                    browseButton.setEnabled(true);
                });
            }

            @Override
            public void onUpdating() {
                runOnUiThread(() -> {
                    statusText.setText("升级中...");
                    statusText.setTextColor(0xFF000000);
                    startButton.setEnabled(false);
                    browseButton.setEnabled(false);
                });
            }
        });

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        String logFileName = "FwOtaUpdate_" + System.currentTimeMillis() + ".log";
        Bundle bundle = new Bundle();
        bundle.putSerializable("logFile", new File(logPath, logFileName));
        logFragment.setArguments(bundle);
        transaction.add(R.id.activity_ota_layout_log, logFragment);
        transaction.commit();

        startButton.setOnClickListener(view -> cardiffOtaUpdate.update(binFileSelection));

        browseButton.setOnClickListener(view -> {
            Intent intent = new Intent(OtaUpdateActivity.this, FileBrowserActivity.class);
            intent.putExtra("file", binFileSelection);
            intent.putExtra("caption", "请选择要写入的固件文件");
            intent.putExtra("type", FileBrowserActivity.TYPE_FILE_ONLY);
            intent.putExtra("ext", "bin");
            startActivityForResult(intent, 1);
        });
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && cardiffOtaUpdate.isUpdating()) {
            Toast.makeText(this, "请等待升级完成！", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 1) {
                File selFile = (File) data.getSerializableExtra("file");
                if (selFile != null && selFile.exists() && selFile.isFile()) {
                    binFileSelection = selFile;
                    currentFileLabelText.setText("当前选定固件文件：");
                    currentFileNameText.setText(selFile.getName());
                    currentFileNameText.setVisibility(View.VISIBLE);
                    return;
                }
            } else if (resultCode == 2) {
                return;
            }
            currentFileLabelText.setText("当前未选定固件文件");
            currentFileNameText.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cardiffOtaUpdate.deinit();
        cardiffOtaUpdate = null;
    }
}
